<template>
  <div class="app-container">
    <div class="filter-container" style="margin-left: 20px;">
      <el-input v-model="listQuery.addressName" placeholder="用户名" style="width: 200px; margin-left: 20px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-select v-model="listQuery.expressfeeId" placeholder="请选择地区" clearable class="filter-item" style="width: 130px; margin-left: 20px;">
        <el-option v-for="item in reginAllList" :key="item.expressfeeId" :label="item.regin+'('+item.expressfeeId+')'" :value="item.expressfeeId" />
      </el-select>
      <!-- <el-input v-model="listQuery.recipientRegion" placeholder="地址名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->
      <el-button v-waves class="filter-item" type="primary" style="margin-left: 20px;" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button> -->
    </div>

    <!--表格内容-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="addressId" sortable="custom" align="center" width="80" :class-name="getSortClass('addressId')">
        <template slot-scope="{row}">
          <span>{{ row.addressId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="userName" sortable="custom" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收件人" prop="recipientName" sortable="custom" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.recipientName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" prop="recipientPhone" sortable="custom" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.recipientPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地区" prop="recipientRegion" sortable="custom" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.recipientRegion }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" prop="recipientAddress" sortable="custom" align="center" width="485">
        <template slot-scope="{row}">
          <span>{{ row.recipientAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findAddress, addAddress, deleteAddress, findRegin } from '@/api/address'
import waves from '@/directive/waves' // waves directive
import moment from 'moment'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null, // 表格集合数据
      total: 0, // 总条数
      listLoading: true,
      listQuery: { // 查询的筛选条件
        page: 1,
        limit: 10,
        addressName: undefined,
        expressfeeId: undefined,
        region: undefined
      },
      reginAllList: '',
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: false,

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        addressName: [{ required: true, message: '品牌名不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() { // 未渲染之前 data加载之后
    this.getList()
    this.getReginList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      findAddress(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        })
      })
    },
    async getReginList() {
      this.listLoading = true
      findRegin(this.listQuery).then(response => {
        this.reginAllList = response.data.list
        // console.log(list)
        // this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        addressId: undefined,
        addressName: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addAddress(this.temp).then(response => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDelete(row) {
      deleteAddress(row.addressId).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
      // this.list.splice(index, 1)
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

  <style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
